﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class User_Address_EditController : UserController
    {
        public IUser_addr_bookService _user_addr_book { get; set; }
        [Authorize]
        [HttpGet]
        public IActionResult Get(int id,string accept_name,string province,string city,string area,string address,string mobile,string telphone,string email,string post_code)
        {
            //检查用户是否登录
            Users userModel = GetUserInfo();
            User_addr_book model = new User_addr_book();
            if (userModel == null)
            {
                return Ok(new { status = 0, msg = "用户尚未登录或已超时!" });
            }
            if (id > 0)
            {
                if (!_user_addr_book.Exists(id, userModel.user_name))
                {
                    return Ok(new { status = 0, msg = "收货地址不存在或已删除!" });
                }
                model = _user_addr_book.GetModel(id);
            }
            //检查收件人
            if (string.IsNullOrEmpty(accept_name))
            {
                return Ok(new { status = 0, msg = "请输入收件人姓名!" });
            }
            //检查省市区
            if (string.IsNullOrEmpty(province) || string.IsNullOrEmpty(city) || string.IsNullOrEmpty(area))
            {
                return Ok(new { status = 0, msg = "请选择您所在的省市区!" });
            }
            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                return Ok(new { status = 0, msg = "请输入收件人的手机!" });
            }
            //保存数据
            model.user_id = userModel.id;
            model.user_name = userModel.user_name;
            model.accept_name = accept_name;
            model.area = province + "," + city + "," + area;
            model.address = address;
            model.mobile = mobile;
            model.telphone = telphone;
            model.email = email;
            model.post_code = post_code;
            if (id > 0)
            {
                _user_addr_book.Update(model);
                return Ok(new { status = 1, msg = "修改收货地址成功!" });
            }
            else
            {
                int address_id=_user_addr_book.Add(model);
                return Ok(new { status = 1, msg = "新增收货地址成功！",address_id = address_id });
            }
        }
    }
}